from django.http import JsonResponse
from django.views import View

from ihome.utils.fastdfs.fastdfs_storage import FastDFSStorage
from wangziye.models import User, House, HouseImage


class AvatarView(View):

    def post(self, request):
        '''头像上传'''
        avatar = request.FILES.get('avatar')

        if not avatar:
            return JsonResponse({"errno": "4302",
                                 "errmsg": "头像获取失败"})
        fdfs = FastDFSStorage()
        file_id = fdfs.save(name=None, content=avatar)

        try:
            User.objects.filter(id=request.user.id).update(avatar=file_id)
        except Exception as e:
            return JsonResponse({'errno': '4001',
                                 'errmsg': '头像保存错误'})

        avatar_url = fdfs.url(file_id)

        return JsonResponse({
            "data": {
                "avatar_url": avatar_url},
            "errno": "0",
            "errmsg": "头像上传成功"
        })


class HouseImagesView(View):

    def post(self, request, house_id):
        '''上传房源'''
        house_image = request.FILES.get('house_image')
        if not house_image:
            return JsonResponse({"errno": "4302",
                                 "errmsg": "头像获取失败"})
        fdfs = FastDFSStorage()
        file_id = fdfs.save(name=None, content=house_image)

        try:
            house = House.objects.get(id=house_id)
            if not house.index_image_url:
                House.objects.filter(id=house_id).update(index_image_url=file_id)

            HouseImage.objects.create(house_id=house_id,
                                      url=file_id)

        except Exception as e:
            return JsonResponse({'errno': '4001',
                                 'errmsg': '图片保存错误'})

        index_image_url = fdfs.url(file_id)

        return JsonResponse({
            "data": {
                "url": index_image_url},
            "errno": "0",
            "errmsg": "图片上传成功"
        })
